<template>
  <div class="article-list">
    <van-pull-refresh v-model="isRefreshLoading" @refresh="onRefresh" :success-text="refreshSuccessText" :success-duration="1500">
        <van-list
        v-model="loading"
        :finished="finished"
        :error.sync="error"
        error-text="请求失败，点击重新加载"
        finished-text="没有更多了"
        @load="onLoad"
      >
        <!-- <van-cell v-for="(article,index) in list" :key="index" :title="article.title" /> -->
        <ArticleItem    ArticleItem
        v-for="(article,index) in list" :key="index" :article="article"></ArticleItem>
      </van-list>
    </van-pull-refresh>
  </div>
</template>

<script>
import { getArticles } from '@/api/article'
import ArticleItem from '@/components/article-item/index.vue'

export default {
  name: 'ArticleList',
  props: {
    channel: {
      type: Object,
      require: true
    }
  },
  components: {
    ArticleItem
  },
  data () {
    return {
      list: [], // 存储列表数据
      loading: false, // 控制加载中loading状态
      finished: false, // 控制数据加载结束
      timestamp: null, // 请求获取下一页数据的时间戳
      error: false, // 控制失败的提示状态
      isRefreshLoading: false, // 控制下拉刷新的loading状态
      refreshSuccessText: '刷新成功' // 设置下拉刷新的提示文本
    }
  },
  methods: {
    async onLoad () {
      // 1.请求获取数据
      try {
        const { data } = await getArticles({
          channel_id: this.channel.id,
          timestamp: this.timestamp || Date.now(), // 请求数据的页码
          with_top: 1
        })
        console.log(data)
        // 2.把请求结果放到list数组中
        const { results } = data.data
        // 把数组元素一个一个拿出来
        this.list.push(...results)

        // 3.本次数据加载结束后要把加载状态设置为结束
        this.loading = false
        // 4.判断数据是否加载完成
        if (results.length) {
          this.timestamp = data.data.pre_timestamp
        } else {
          this.finished = true
        }
      } catch (err) {
      //  展示错误状态
        this.error = true
        // 出现错误，把loading关闭
        this.loading = false
      }
    },
    // 下拉刷新调用该函数
    async onRefresh () {
      try {
        // 请求获取数据
        const { data } = await getArticles({
          channel_id: this.channel.id,
          timestamp: Date.now(), // 下拉刷新，每次获取最新数据，所以要拿到最新的时间戳
          with_top: 1
        })
        if (Math.random() > 0.4) {
          JSON.parse('asdsafdee')
        }
        // 将数据放到列表顶部
        this.list.unshift(...data.data.results)
        // 关闭下拉刷新的状态
        this.isRefreshLoading = false
        // 更新下拉刷新成功提示的文本
        this.refreshSuccessText = `刷新成功，更新了${data.data.results.length}条数据`
      } catch (error) {
        this.isRefreshLoading = false
        this.refreshSuccessText = '刷新失败'
      }
    }
  }

}
</script>

<style lang="less" scoped>
.article-list {
  height: 79vh;
  overflow-y: auto;
}
</style>
